import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

from job.src.function.strencode import str_decode


class GetSessionAndToken():
    def __init__(self, isClose=True):
        options = webdriver.ChromeOptions()
        if isClose:
            options.add_argument('--headless')
        self.browser = webdriver.Chrome(options=options)

    # 登录系统，具体到自己系统时需要自行修改 634832692FFCB971B5F7BD2E9D0D6F85
    def login_system(self, **params):
        username = params['username']
        password = str_decode(params['password'])
        url = params['jira_url']
        self.browser.get(url)
        # 显性等待，直到用户名控件加载出来才进行下一步
        WebDriverWait(self.browser, 20, 0.5).until(EC.presence_of_element_located((By.ID, "username")))
        self.browser.find_element_by_id("username").send_keys(username)
        self.browser.find_element_by_id("password").send_keys(password)
        self.browser.find_element_by_xpath('//*[@id="submit_psd"]/input').click()
        time.sleep(4)

    def openURL(self, url):
        self.browser.get(url)

    def get_cookie(self):
        cookies = self.browser.get_cookies()
        # print('cookies:', cookies)
        return cookies

    # 获取sessionid
    def get_sessionid(self):
        # 是要从localStorage中获取还是要从sessionStorage中获取，具体看目标系统存到哪个中
        # window.sessionStorage和直接写sessionStorage是等效的
        # 一定要使用return，不然获取到的一直是None
        # get的Item不一定就叫sessionId，得具体看目标系统把sessionid存到哪个变量中
        sessionid = self.browser.execute_script('return sessionStorage.getItem("sessionId");')

        # 另外sessionid一般都直接通过返回Set-Cookies头设置到Cookie中，所以也可以从Cookie读取
        # 获取浏览器所有Set-Cookie，返回对象是字典列表
        # cookies = self.browser.get_cookies()
        # 获取单项Cookie，是不是叫sessionId取决于系统存成什么变量，单项Cookie是字典
        # cookie = self.browser.get_cookie("sessionId")
        # cookie = cookie["value"]
        # print(f"{cookies}")
        return sessionid

    # 获取token
    def get_token(self, keyName):
        # 是要从localStorage中获取还是要从sessionStorage中获取，具体看目标系统存到哪个中
        # window.sessionStorage和直接写sessionStorage是等效的
        # 一定要使用return，不然获取到的一直是None
        # get的Item不一定就叫token，得具体看目标系统把token存到哪个变量中
        # token = self.browser.execute_script('return sessionStorage.getItem("token");')
        # 'return se.SEConfig.token;'  --- ts登录的tooken
        cmd_js = f'return {keyName};'
        token = self.browser.execute_script(cmd_js)
        # print(f"token: {token}")
        return token

    def close(self):
        # 退出程序时关闭浏览器
        self.browser.close()

if __name__ == "__main__":
    obj = GetSessionAndToken()
    obj.login_system()
    sessionid = obj.get_cookie()
    jssion = sessionid['value']
    print(f"sessionid为： {jssion}")